package com.zisu.wcsopcua.opcua.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zisu.wcsopcua.common.utils.CommonFunction;
import com.zisu.wcsopcua.opcua.constant.PLCConstant;
import com.zisu.wcsopcua.opcua.selfunion.entity.SubscribeVarOfConfigEntity;
import org.eclipse.milo.opcua.stack.core.security.SecurityPolicy;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;


public class LocalMulPLCConfig {

    //读取json文件
    public static String readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            if (!jsonFile.exists()) {
                boolean b= jsonFile.createNewFile();
                JSONObject json = new JSONObject();
                json =JSON.parseObject("{\"config\": [],\"subscribedForVisit\":{}}");
                FileWriter fw = new FileWriter(jsonFile.getAbsoluteFile());
                BufferedWriter bw = new BufferedWriter(fw);
                json.writeJSONString(bw);
                bw.close();
            }

            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), StandardCharsets.UTF_8);
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) throws IOException {
//        SubscribeVarOfConfigEntity subscribeVarOfConfigEntity1 = new SubscribeVarOfConfigEntity(5,"Boolean",3000,"plc2");
//        SubscribeVarOfConfigEntity subscribeVarOfConfigEntity2 = new SubscribeVarOfConfigEntity(5,"Byte",2000,"plc2");
//        SubscribeVarOfConfigEntity subscribeVarOfConfigEntity3 = new SubscribeVarOfConfigEntity(5,"Double",1000,"plc2");
//        SubscribeVarOfConfigEntity subscribeVarOfConfigEntity4 = new SubscribeVarOfConfigEntity(5,"Float",1000,"plc2");
//        ArrayList<SubscribeVarOfConfigEntity> objects = new ArrayList<>();
//        objects.add(subscribeVarOfConfigEntity1);
//        objects.add(subscribeVarOfConfigEntity2);
//        objects.add(subscribeVarOfConfigEntity3);
//        objects.add(subscribeVarOfConfigEntity4);
//        writeIntoFileOfSubscribeVar(objects);


        //read
        ArrayList<SubscribeVarOfConfigEntity> plc1 = getSubscribedVarOfConfig("plc2");
        Map<Integer, List<SubscribeVarOfConfigEntity>> map = plc1.stream().collect(Collectors.groupingBy(t -> t.getPeriod()));
        System.out.println("period"+map);
        /*然后再对map处理，这样就方便取出自己要的数据*/
        for(Map.Entry<Integer, List<SubscribeVarOfConfigEntity>> entry : map.entrySet()){
            System.out.println("key:"+entry.getKey());
            System.out.println("value:"+entry.getValue());
        }
        System.out.println();
    }

    //把修改了的变量 全量替换到文件
    public static void writeIntoFileOfSubscribeVar(List<SubscribeVarOfConfigEntity> subscribeVars) throws IOException {
        String s = "";
        String ss = "";
        if(CommonFunction.isLinux()){
            s = readJsonFile(PLCConstant.localURLForLinux);
            ss = PLCConstant.localURLForLinux;

        }else if(CommonFunction.isWindows()){
            s = readJsonFile(PLCConstant.localURLForWindows);
            ss = PLCConstant.localURLForWindows;
        }

        JSONObject jobj = JSON.parseObject(s);

        //JSONArray subscribedForVisits = jobj.getJSONArray("subscribedForVisit");//构建JSONArray数组
        JSONObject subscribedForVisit = jobj.getJSONObject("subscribedForVisit");
        if(subscribeVars.size() <= 0){
            return;
        }


        String plcName = subscribeVars.get(0).getPlcName();
        JSONArray objects = new JSONArray();



        for (SubscribeVarOfConfigEntity entity:subscribeVars){
            Map<String, Object> newValue = new LinkedHashMap<String, Object>();
            newValue.put("plc_name", entity.getPlcName());
            newValue.put("ns", entity.getNameSpace());
            newValue.put("period", entity.getPeriod());
            newValue.put("identity", entity.getIdentifier());
            objects.add(newValue);
        }
        subscribedForVisit.put(plcName,objects);


        JSONObject json = jobj;


        File file = new File(ss);


        if (!file.exists()) {
            boolean b= file.createNewFile();

        }
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        json.writeJSONString(bw);
        bw.close();
        System.out.println("end");
        //写入json 结束
    }

    public static ArrayList<SubscribeVarOfConfigEntity> getSubscribedVarOfConfig(String plcName){
        //String path = LocalMulPLCConfig.class.getClassLoader().getResource("mulPLCConfig.json").getPath();
        String s = "";
        if(CommonFunction.isLinux()){
            CommonFunction.createDirIfNotExit(PLCConstant.localURLDirForLinux);
            s = readJsonFile(PLCConstant.localURLForLinux);
        }else if(CommonFunction.isWindows()){
            CommonFunction.createDirIfNotExit(PLCConstant.localURLDirForWindows);
            s = readJsonFile(PLCConstant.localURLForWindows);
        }

        JSONObject jobj = JSON.parseObject(s);



        JSONObject subscribedForVisit = jobj.getJSONObject("subscribedForVisit");//构建JSONArray数组
        JSONArray jsonObject = subscribedForVisit.getJSONArray(plcName);
        if(jsonObject == null){
            return new ArrayList<>();
        }
        ArrayList<SubscribeVarOfConfigEntity> res = new ArrayList<>();
        for (int i = 0 ; i < jsonObject.size();i++){
            JSONObject key = (JSONObject)jsonObject.get(i);

            Integer period = (Integer)key.get("period");
            Integer ns = (Integer)key.get("ns");
            String identity =(String)key.get("identity");
            res.add(new SubscribeVarOfConfigEntity(ns,identity,period,plcName));
        }
        return res;
    }

    public static HashMap<String,PLCConfig> getPLCConfig(){
        //String path = LocalMulPLCConfig.class.getClassLoader().getResource("mulPLCConfig.json").getPath();
        String s = "";
        if(CommonFunction.isLinux()){
            CommonFunction.createDirIfNotExit(PLCConstant.localURLDirForLinux);
            s = readJsonFile(PLCConstant.localURLForLinux);
        }else if(CommonFunction.isWindows()){
            CommonFunction.createDirIfNotExit(PLCConstant.localURLDirForWindows);
            s = readJsonFile(PLCConstant.localURLForWindows);
        }

        JSONObject jobj = JSON.parseObject(s);



        JSONArray movies = jobj.getJSONArray("config");//构建JSONArray数组

        HashMap<String,PLCConfig> res = new HashMap<>();
        for (int i = 0 ; i < movies.size();i++){
            JSONObject key = (JSONObject)movies.get(i);
            String plcName = (String)key.get("plc_name");
            String url_config = (String)key.get("endpointUrl_config");
            String policy_config = (String)key.get("securityPolicy_config");
            String[] user_config =((String)key.get("identityProvider_config")).isEmpty()?null:((String)key.get("identityProvider_config")).split(",");
            String ip = (String)key.get("ip");
            Integer messageMode = (Integer)key.get("messageMode_config");
            res.put(plcName,new PLCConfig(plcName,url_config, SecurityPolicy.valueOf(policy_config),user_config,ip,messageMode));
        }
        return res;
    }
}
